package com.bxd.baodan.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.bxd.baodan.App;
import com.bxd.baodan.R;
import com.bxd.baodan.app.Constant;
import com.bxd.baodan.app.JsonApi;
import com.bxd.baodan.app.LoginInfo;
import com.bxd.baodan.item.UserItem;
import com.bxd.baodan.util.AppManager;
import com.bxd.baodan.util.ETUtil;
import com.bxd.baodan.util.JSONUtil;
import com.bxd.baodan.util.LoginIMUtil;
import com.bxd.baodan.util.NetUtil;
import com.bxd.baodan.util.SaveMsgUtil;

/**
 * Created by lizhichao on 17/7/27.
 */

public class BindPhoneActivity extends BaseActivity implements View.OnClickListener {
    private TextView codeBtn;
    private LoginActivity.ThirdInfo thirdInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bind_phone);
        setActionBarTitle("绑定手机");

        thirdInfo = new Gson().fromJson(getIntent().getExtras().getString("thirdinfo"), LoginActivity.ThirdInfo.class);


        findViewById(R.id.bind).setOnClickListener(this);
        codeBtn = (TextView) findViewById(R.id.code_btn);
        codeBtn.setOnClickListener(this);

    }

    private EditText getPhone() {
        return (EditText) findViewById(R.id.phone);
    }

    private EditText getCode() {
        return (EditText) findViewById(R.id.code);
    }

    @Override
    public void onClick(View view) {

        String phone, code;
        switch (view.getId()) {
            case R.id.bind:

                phone = getPhone().getText().toString().trim();
                if (phone.isEmpty()) {
                    showToast("请输入手机号");
                    return;
                }
                if (!ETUtil.isMobileNO(getPhone())) {
                    showToast("手机号格式不对");
                    return;
                }
                code = getCode().getText().toString().trim();
                if (code.isEmpty()) {
                    showToast("验证码不能为空");
                    return;
                }

                //请求成功 ,关闭倒计时
                getBind(phone, code);


                break;

            case R.id.code_btn:
                phone = getPhone().getText().toString().trim();
                if (phone.isEmpty()) {
                    showToast("手机号不能为空");
                    return;
                }
                if (!ETUtil.isMobileNO(getPhone())) {
                    showToast("手机号格式不对");
                    return;
                }
                startTime();
                NetUtil netUtil = new NetUtil(this, JsonApi.GET_CHECK_VCODE);
                netUtil.
                        setParams("phone", phone);
                netUtil.setParams("src", "4");
                netUtil.postRequest("正在获取验证码", new NetUtil.RequestStringListener() {
                    @Override
                    public void onComplete(String result) {
                        if (JSONUtil.isSuccess(result)) {
                        }
                    }
                });

                break;
        }
    }

    private void getBind(String phone, String code) {
        NetUtil netUtil = new NetUtil(this, JsonApi.user_bindphone);

//        phone 手机号
//        captcha验证码
//        avatar 头像
//        nickname(昵称，/^[\x{4e00}-\x{9fa5}a-z]{2,10}$/ui)
//        gender0未知1男2女
//        province 省
//        city市
//        birthday出生日期，如2017-07-12
//        openid从第三方接口获取的openid
//        thirdparty第三方登录的标识 wechat, qq, sina中的一个


        int sex = 0;
        if (thirdInfo.gender.equals("男")) {
            sex = 1;
        } else if (thirdInfo.gender.equals("女")) {
            sex = 2;
        }

        netUtil.setParams("phone", phone);
        netUtil.setParams("captcha", code);


        netUtil.setParams("avatar", thirdInfo.iconurl);
        netUtil.setParams("nickname", thirdInfo.name);
        netUtil.setParams("gender", sex);
        netUtil.setParams("openid", thirdInfo.uid);
        netUtil.setParams("thirdparty", thirdInfo.platform);


        netUtil.postRequest("", new NetUtil.RequestStringListener() {
            @Override
            public void onComplete(String result) {
                if (JSONUtil.isSuccess(result)) {
                    LoginInfo loginInfo = LoginInfo.getInstance(BindPhoneActivity.this);
                    loginInfo.saveUserInfo(JSONUtil.getData(result),
                            App.getContext());
                    // TODO: 17/7/27 绑定之后再save  用户信息是否增加字段
//						SpUtil.getInstance().savaString(
//								SharedPreferanceKey.ACCOUNT,
//								loginInfo.getAccount());
                    UserItem user = LoginInfo.getInstance(
                            App.getContext()).getUser();

                    SaveMsgUtil.updateLocalInfo(user,
                            App.getContext());// 更新用户的登录资料到本地
                    App.getContext().sendBroadcast(
                            new Intent(Constant.ACTION_SUCCESS_LOGIN));
                    App.getContext().sendBroadcast(
                            new Intent(Constant.ACTION_SUCCESS_UPLOAD_INFOR));


                    loginIM();  //IM登录
                    AppManager.getInstance().finishOtherActivity(MainActivity.class);
                }
            }
        });

    }


    public void loginIM() {
        LoginIMUtil loginUtil = new LoginIMUtil(AppManager.getInstance().currentActivity());
        loginUtil.initIM();
        loginUtil.setCallback(new LoginIMUtil.Callback() {
            @Override
            public void next() {

            }
        });
        loginUtil.loginIM();
    }

    private int time = -1;
    private Boolean isGetVcode = false;

    /**
     * 开始计时
     */
    private void startTime() {
        time = 60;
        isGetVcode = true;
        new Thread() {
            public void run() {
                do {
                    try {
                        Thread.sleep(1 * 1000);
                        if(handler != null) {
                            handler.sendEmptyMessage(--time);
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } while (time > 0 && isGetVcode == true);
                time = -1;
                handler.sendEmptyMessage(--time);
            }
        }.start();
    }


    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what > 0) {
                codeBtn.setText(msg.what + "秒后重新获取");
                codeBtn.setEnabled(false);
            } else {
                codeBtn.setText("重新获取验证码");
                codeBtn.setEnabled(true);
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
            handler = null;

        }
    }
}
